package com.tpshion.cloud.core.interceptor;

import com.tpshion.cloud.common.support.Field;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.UUID;

/**
 * MVC请求日志拦截器
 */
@Component
public class RequestLogInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(RequestLogInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求开始时间
        request.setAttribute(Field.START_TIME, getTime());
        // 设置唯一请求id，以便于追踪请求链路
        request.setAttribute(Field.TRACE_ID,getTraceId());
        // 打印请求方法和请求地址
        log.info("\r\n--------------------  [{}]  {} start ------------------",request.getMethod(),request.getServletPath());
        log.info("request traceId={}",request.getAttribute(Field.TRACE_ID));
        log.info("queryString:{}",request.getQueryString());
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        long costTime = getTime() - (long)request.getAttribute(Field.START_TIME);
        log.info("\r\n--------------------  [{}]  {} end cost:{}ms ------------------",request.getMethod(),request.getServletPath(),costTime);
    }

    private long getTime(){
        return LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    }

    private String getTraceId(){
        return UUID.randomUUID().toString();
    }

}
